package com.ligq.h265toupinpush.avmetting

import android.content.Context
import android.hardware.Camera
import android.util.AttributeSet
import android.util.Log
import android.view.SurfaceHolder
import android.view.SurfaceView

const val TAG = "meeting_ligq"

class LocalSurfaceView(
    context: Context?,
    attrs: AttributeSet?,
    defStyleAttr: Int,
    defStyleRes: Int
) : SurfaceView(context, attrs, defStyleAttr, defStyleRes), SurfaceHolder.Callback,
    Camera.PreviewCallback {
    private lateinit var mCamera: Camera
    lateinit var size: Camera.Size
    private lateinit var encoder: MeetingH264Encoder

    constructor(context: Context?) : this(context, null)

    constructor(context: Context?, attrs: AttributeSet?) : this(context, attrs, 0)

    constructor(context: Context?, attrs: AttributeSet?, defStyle: Int) : this(
        context,
        attrs,
        defStyle,
        0
    )

    init {
        holder.addCallback(this)
    }

    override fun surfaceCreated(holder: SurfaceHolder) {
        Log.d(TAG, "surfaceCreated: ")
        mCamera = Camera.open(Camera.CameraInfo.CAMERA_FACING_FRONT)
        val parameters = mCamera.parameters
        size = parameters.previewSize
        mCamera.addCallbackBuffer(ByteArray(size.width * size.height * 3 / 2))
        mCamera.setPreviewCallbackWithBuffer(this)
        mCamera.setPreviewDisplay(holder)
        mCamera.setDisplayOrientation(90)
        mCamera.startPreview()
    }

    override fun surfaceChanged(holder: SurfaceHolder, format: Int, width: Int, height: Int) {
        Log.d(TAG, "surfaceChanged: ")
    }

    override fun surfaceDestroyed(holder: SurfaceHolder) {
        Log.d(TAG, "surfaceDestroyed: ")
    }

    override fun onPreviewFrame(data: ByteArray?, camera: Camera?) {
        if (this::encoder.isInitialized) {
            data?.let {
                encoder.encode(it)
            }
        }
        mCamera.addCallbackBuffer(data)
    }

    fun startCapture(socketLive: SocketLive) {
        if (!this::encoder.isInitialized) {
            encoder = MeetingH264Encoder(socketLive)
            encoder.initEncoder(size.width, size.height)
        }
    }
}